<template>
    <div>
        <el-button type="primary" size="small" plain @click="generate">试卷导出</el-button>
    </div>
</template>
<script setup>
import { ref } from 'vue';
import docxtemplater from 'docxtemplater';
import { saveAs } from 'file-saver';
import 'pizzip/dist/pizzip.js'
import 'pizzip/dist/pizzip-utils.js'
import ImageModule from 'docxtemplater-image-module-free';
import { getBase64Sync, base64DataURLToArrayBuffer } from '@/utils/imageUtils'; // 确保你已经创建了这个 utils 文件并导出了相关函数
import { GetPaperCompleteInfo } from '@/api/paper';
import expressionParser from 'docxtemplater/expressions'
import { useClassStore } from '@/stores/modules/class'
const classStore = useClassStore()
const class_name = classStore.classInfo.class_name
const grade_name = classStore.classInfo.grade_name
const props = defineProps({ paperId: Number });
const acs_id = classStore.classInfo.user_and_acs_id

const loadFile = (url, callback) => {
    PizZipUtils.getBinaryContent(url, callback);
}
const toChineseNumeral=(num)=> {
    const chineseNumeral = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
    return chineseNumeral[num - 1];
}
const pattern = /(\d{4}-\d{4})(第[一二三四五六七八九十百千万]+学期)/;
const generate = async () => {
    const res = await GetPaperCompleteInfo(props.paperId, acs_id);
    const answer1 = res.data.data;
    console.log("answer1", answer1);
    const imageUrl = '../../public/image.png';
    const imageBase64 = await getBase64Sync();
    // 准备好的数据，包括转换后的图片
    // const data = {
    //     name:'jakl',
    //     imageBase64: imageBase64 // 确保数据模板中有对应的标签
    // };
    const data = {
        questionInfoByType: [
            {
                type: "多项选择题",
                num: 10,
                score: 20,
                src: imageBase64,
                questions: [
                    {
                        questionContent: "多项选择题题干1",
                        options:[
                            "a0000  ", "B  \n", "C  ", "D  \n"
                        ]
                    },
                    {
                        questionContent: "多项选择题题干2",
                    },
                    {
                        questionContent: "多项选择题题干3",
                    },
                ]
            },
            {
                type: "单项选择题",
                num: 20,
                score: 200,
                src: imageBase64,
                questions: [
                    {
                        questionContent: "题干1",
                        options: [
                            "a0000  ", "B  \n", "C  ", "D  \n"
                        ]
                    },
                    {
                        questionContent: "题干2",
                        options: [
                            "a111  ", "B  \n", "C  ", "D  \n"
                        ]
                    },
                    {
                        questionContent: "题干3",
                        options: [
                            "a222  ", "B  \n", "C  ", "D  \n"
                        ]
                    },
                ]
            },
            {
                type: "填空题",
                num: 10,
                score: 10,
                src: imageBase64,
                questions: [
                    {
                        questionContent: "填空题题干1",
                    },
                    {
                        questionContent: "填空题题干2",
                    },
                    {
                        questionContent: "填空题题干3",
                    },
                ]
            },

        ]


    }  
    const match = grade_name.match(pattern);
    const academicYear = match[1];
    const semester = match[2];
    answer1.paper.academyYear = academicYear
    answer1.paper.term = semester
    answer1.paper.class=class_name
    answer1.questionInfoByType.forEach((item, index) => {
        item.type = `${toChineseNumeral(index + 1)}、${item.type}`;
        item.src = imageBase64
        if(item.type.indexOf("选择题") === -1){
            item.questions.forEach((subItem, index) => {
                delete subItem.options
            });
        }
    });
    // data.questionInfoByType.forEach((item, index) => {
    //     item.type = `${toChineseNumeral(index + 1)}、${item.type}`;
    // });
    loadFile("/public/template1.docx", function (error, content) {
        if (error) {
            throw error;
        };
        let zip = new PizZip(content);
        const imageModule = new ImageModule({
            getImage: (tagValue) => base64DataURLToArrayBuffer(tagValue),
            getSize: () => [90, 45] //设置图片大小
        });
        const doc = new docxtemplater(zip, {
            modules: [imageModule],
            linebreaks: true,
            parser: expressionParser
        });
        // const doc = new docxtemplater(zip, { linebreaks: true }).attachModule(new ImageModule({
        //     getImage: (tagValue) => base64DataURLToArrayBuffer(tagValue),
        //     getSize: () => [90, 45] //设置图片大小
        // }));
        //  If you're using version 4 of docxtemplater, the way modules are attached has changed compared to version 3. The attachModule function is no longer used; instead, modules are passed as an option to the constructor. Here's how you should initialize docxtemplater with the ImageModule in version 4:
        doc.setData(answer1);
        try {
            doc.render();
        } catch (error) {
            let e = {
                message: error.message,
                name: error.name,
                stack: error.stack,
                properties: error.properties,
            };
            console.log(JSON.stringify({ error: e }));
            throw error;
        }
        let out = doc.getZip().generate({
            type: "blob",
            mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        });
        saveAs(out, "导出的试卷.docx");
    });
}
</script>

<style scoped></style>
